<?php

class Dwoo_Plugin_image extends Dwoo_Plugin { 
	public function process($variable, $fieldName, $width = null, $height = null, array $rest = array()) {
		$value = $this->dwoo->readVar($variable);
		$style = '';
		if($width !== null) {
			$style .= sprintf(' width: %d px;', $width);
		}
		if($height !== null) {
			$style .= sprintf(' height: %d px;', $height);
		}
		
		
		$execContainer = $this->dwoo->readVarInto('container', $this->dwoo->getData());
		$routing = $execContainer->getContext()->getRouting();
		if($value || !$execContainer->getAttribute('isEditing', 'org.welcomescreen', false)) {
			$html = sprintf('<img src="%s" style="%s" />', htmlspecialchars($value, ENT_QUOTES, 'utf-8'), $style);
			return $html;
		} else {
			$fileUploadUrl = $routing->gen('backend.visits.uploadFile', array(), array('relative' => false));
			
			$funcName = $this->randomId();
			$imageId = $this->randomId();
			$fileInputId = $this->randomId();
			
			$html = sprintf('
				<script type="text/javascript">
					function %s(data) {
						parent.visitFormElementChanged("%s", data.path);
						var imageNode = dojo.byId("%s");
						imageNode.src = data.path;
						dojo.style(imageNode, "display", "inline");
					}
				</script>
			', $funcName, addslashes($fieldName), $imageId);
			$html .= sprintf('
				<img id="%s" src="about:blank" style="display:none; %s" />
			', $imageId, $style);
			$html .= sprintf('
				<input id="%s" name="file" type="file" dojoType="dojox.form.FileInputBlind" url="%s" onComplete="%s">
			', $fileInputId, $fileUploadUrl, $funcName);
			
			return $html;
		}
	}
	
	protected function randomId() {
		return 'id_' . preg_replace('#[^a-z0-9]#', '', AgaviToolkit::uniqid());
	}
}

/*
<input dojoType="dojox.form.FileInputAuto" id="defaultAuto2onchange" blurDelay="10" name="inputFileAuto2" triggerEvent="onchange" url="../resources/RecieveFile.php" onComplete="sampleCallback"/>
var inputNode = dojo.create('input', {type: 'file'}, wrapperNode);
var input = new dojox.form.FileInputBlind({
	name: "file",
	url: fileUploadUrl,
	onComplete: function(data,ioArgs,widgetRef) {
		dojo.create('input', {type: 'hidden', value: data.path, name: inputName}, variablesContainer);
	}
}, inputNode);

*/
?>